package cn.com.thinvent.dispatch.service.biz.impl;

import cn.com.thinvent.dispatch.dao.OrderDetailMapper;
import cn.com.thinvent.dispatch.dao.OrderMainMapper;
import cn.com.thinvent.dispatch.entity.OrderDetail;
import cn.com.thinvent.dispatch.entity.OrderMain;
import cn.com.thinvent.dispatch.entity.response.OrderDetailResponse;
import cn.com.thinvent.dispatch.entity.response.OrderMainResponse;
import cn.com.thinvent.dispatch.service.biz.OrderService;
import cn.com.thinvent.dispatch.service.biz.util.DataConvertUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMainMapper orderMainMapper;

    @Resource
    private OrderDetailMapper orderDetailMapper;

    @Override
    public void placeOrder(OrderMain orderMain, List<OrderDetail> orderDetails) {
        orderMainMapper.insertOrderMain(orderMain);
        for (OrderDetail orderDetail : orderDetails) {
            orderDetailMapper.insertOrderDetail(orderDetail);
        }
    }

    @Override
    public List<OrderMainResponse> findOrdersByUserId(String userId) {
        List<OrderMainResponse> orderMainResponses = new ArrayList<>();
        List<OrderMain> recentOrdersByCreatedById = orderMainMapper.findRecentOrdersByCreatedById(userId);
        // 获取详情信息
        List<String> orderIds = recentOrdersByCreatedById.stream().map(OrderMain::getId).collect(Collectors.toList());
        List<OrderDetail> orderDetails = orderDetailMapper.selectOrderDetailsByOrderIds(orderIds);
        List<OrderDetailResponse> orderDetailsList = new ArrayList<>();
        DataConvertUtils.convertDOList2DTOList(orderDetails, orderDetailsList, OrderDetailResponse.class);
        // 使用 Stream API 按照 orderId 分组
        Map<String, List<OrderDetailResponse>> groupedOrderDetailsList = orderDetailsList.stream()
                .collect(Collectors.groupingBy(OrderDetailResponse::getOrderId));
        DataConvertUtils.convertDOList2DTOList(recentOrdersByCreatedById, orderMainResponses, OrderMainResponse.class);
        orderMainResponses.stream().forEach(orderMainResponse -> {
            List<OrderDetailResponse> orderDetailResponses = groupedOrderDetailsList.get(orderMainResponse.getId());
            orderMainResponse.setOrderDetails(orderDetailResponses);
        });
        return orderMainResponses;
    }
}
